package kr.hkit.androidcomplete02.ch19;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class LongTime5 extends Activity {
	int mValue;
	TextView tv;
	ProgressDialog mProgress;
	public static final String TAG = "ASYNCTASK";
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_uploadex);
		
		tv = (TextView) findViewById(R.id.ch19_uploadex_tv);
	}
	
	public void mOnClick(View v){
		Log.d(TAG, "mOnClick()");
		new AccumulateTask().execute(100, 200);
	}
	
	class AccumulateTask extends AsyncTask<Integer, Integer, Integer>{
		protected void onPreExecute() {
			Log.d(TAG, "onPreExecute()");
			super.onPreExecute();
			
			mProgress = new ProgressDialog(LongTime5.this);
			mProgress.setTitle("Updating");
			mProgress.setMessage("Wait...");
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setProgress(0);
			mProgress.setCancelable(false);
			mProgress.setButton(ProgressDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					cancel(true);
				}
			});
			mProgress.show();
		}
		
		protected Integer doInBackground(Integer... params) {
			Log.d(TAG, "doInBackground() : " + params[0] + ", "+ params[1]);
			
			if(mValue == 0 || mValue == params[1]+1) mValue = params[0];
			
			while(isCancelled() == false){
				mValue++;
				if(mValue <= params[1]){
					publishProgress(mValue);
				} else {
					break;
				}
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			return mValue;
		}
		
		protected void onProgressUpdate(Integer... values) {
			Log.d(TAG, "onProgressUpdate() : " + values[0]);
			
			mProgress.setProgress(values[0]/2);
			tv.setText(Integer.toString(values[0]));
		}
		
		protected void onPostExecute(Integer result) {
			Log.d(TAG, "onPostExecute() : " + result);
			mProgress.dismiss();
			mValue = 0;
		}
		
		protected void onCancelled() {
			Log.d(TAG, "onCancelled()");
			mProgress.dismiss();
		}
		
	}
}
